package me.illtamer.infinite;

import lombok.extern.slf4j.Slf4j;
import me.illtamer.infinite.factory.SingletonFactory;
import me.illtamer.infinite.file.loader.FileManager;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;

import java.util.Collections;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Slf4j
public class TranslateController {

    private final ExecutorService commandService = Executors.newSingleThreadExecutor(
            new BasicThreadFactory.Builder().namingPattern("Command-Pool-%d").priority(10).daemon(true).build());

    private final Scanner scanner = new Scanner(System.in);
    // 选择状态标识
    private boolean select = false;

    private TranslateController() {
        start();
    }

    public void refresh() {
        System.out.println("检测到 source 目录内容变动, 刷新状态中 ...");
        select = false;
        showFiles();
    }

    private void start() {
        commandService.execute(() -> {
            System.out.println("==> 添加完待翻译文件后，按下列说明进行输入即可 <==");
            while (true) {
                if (!select) showFiles();

                if (select && scanner.hasNext()) {
                    Set<String> input = parseInput(scanner.next());
                    if (input == null || input.size() == 0) {
                        System.out.println("您的输入有误，请检查");
                        continue;
                    }
                    System.out.println("分配线程中，请稍后 ...");
                    // 分配翻译任务(用户输入 选择文件)
                    FileManager.dispatchFileParser(input);
                    select = false;
                } else {
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    private Set<String> parseInput(String input) {
        Set<String> nameSet = FileManager.linkedFileNameSet();
        String[] split = input.split("\\s");
        if (split.length == 1 && "*".equals(split[0]))
            return nameSet;
        try {
            Set<Integer> selects = new TreeSet<>();
            for (String s : split)
                selects.add(Integer.parseInt(s));
            AtomicInteger i = new AtomicInteger();
            return nameSet.stream().filter(name -> selects.contains(i.getAndIncrement())).collect(Collectors.toSet());
        } catch (NumberFormatException e) {
            log.debug("Bad input = =, please check first !", e);
            return Collections.emptySet();
        }
    }

    private void showFiles() {
        StringBuilder builder = new StringBuilder("已加载的支持转换的文件列表 ->" +
                "\n (键入文件序号并以 空格 相连以执行相应的文件翻译)" +
                "\n (若仅键入 * 则表示开始对全部支持文件进行翻译)");
        AtomicInteger i = new AtomicInteger();
        FileManager.linkedFileNameSet().forEach(name ->
                builder.append("\n")
                        .append("> [").append(i.getAndIncrement()).append("] |")
                        .append(name)

        );
        System.out.println(builder);
        select = true;
    }

    public static void newInstance() {
        SingletonFactory.getSingleton(TranslateController.class);
    }

}
